//when document is loaded...
$(document).ready(function() {
    setTimeout(overrideAjaxCart, 200);
});

function overrideAjaxCart() {
    if (isAjaxCartEnabled == 1) {
        var origUpdateCart = ajaxCart.updateCart;
        ajaxCart.updateCart = function(data) {
            origUpdateCart(data);
            replaceClickHandler();
        }
    }

    replaceClickHandler();
}


function replaceClickHandler() {
    //for every 'add' buttons...
    $('.ajax_add_to_cart_button').unbind('click').click(function() {
        var idProduct = $(this).attr('rel').replace('ajax_id_product_', '');
        if ($(this).attr('disabled') != 'disabled') {
            checkSellers(idProduct, null, false, this);
            return false;
        }
    });

    //for product page 'add' button...
    $('body#product p#add_to_cart input').unbind('click').click(function() {
        checkSellers($('#product_page_product_id').val(), $('#idCombination').val(), true, null, $('#quantity_wanted').val(), null);
        return false;
    });
}

function checkSellers(idProduct, idCombination, addedFromProductPage, callerElement, quantity, whishlist) {
    var url = module_dir + 'ajax_checkseller.php';
    //alert(url);
    $.get(url, { id_product: idProduct },
            function(data) {
                if (data == 'OK') {
                    if (isAjaxCartEnabled == 1) {
                        ajaxCart.add(idProduct, idCombination, addedFromProductPage, callerElement, quantity, whishlist);
                        return false;
                    }
                    else {
//                        alert(callerElement);
                        if (callerElement != null) window.location.href = $(callerElement).attr("href");
                        else $('form#buy_block').submit();
                        return true;
                    }
                } else {
                    //show error message
                    alert(data);
                    return false;
                }
            });
}


